package com.rdxer.service;

import com.rdxer.model.Attachment;
import com.rdxer.repository.AttachmentRepository;
import com.rdxer.core.utils.IdWorker;
import com.rdxer.core.utils.SearchUtils;
import com.rdxer.core.utils.search.SearchPara;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AttachmentService {
    @Autowired
    private AttachmentRepository repository;

    @Autowired
    private IdWorker idWorker;

    public void clear(){
        repository.deleteAll();
    }
    /**
     * 查询全部列表
     * @return
     */
    public List<Attachment> findAll() {
        return repository.findAll();
    }

    /**
     * 根据ID查询实体
     * @param id
     * @return
     */
    public Attachment findById(Long id){
        return repository.findById(id).orElseThrow(()->{return new RuntimeException("未找到信息");});
    }

    /**

     * @param attachment
     */
    public Attachment add(Attachment attachment) {
        attachment.setId(idWorker.nextId());
        attachment.setCreatedDate(System.currentTimeMillis());
        // 雪花分布式ID生成器
        return repository.save(attachment);
    }

    /**
     * 修改
     * @param role
     */
    public Attachment update(Attachment role) {
        return repository.save(role);
    }

    /**
     * 删除
     * @param id
     */
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    /**
     * 条件查询+分页
     */
    public Page<Attachment> search(SearchPara para) {
        return SearchUtils.searchByPage(repository, para);
    }
    /**
     * 条件查询
     */
    public List<Attachment> searchNoPage(SearchPara para) {
        return SearchUtils.searchAll(repository,para);
    }

    public Attachment findByUrl(String url) {
        return repository.findByUrl(url);
    }
}